import json
import os
import re
from typing import Dict, List, Union

def extract_code_blocks(content: str) -> List[Dict[str, str]]:
    """
    Extract code blocks from content using triple backtick pattern
    
    Args:
        content: String content that may contain code blocks
        
    Returns:
        List of dictionaries containing language and code content
    """
    code_blocks = []
    pattern = r'```(\w+)?\n(.*?)```'
    matches = re.finditer(pattern, content, re.DOTALL)
    
    for match in matches:
        language = match.group(1) or ''
        code_content = match.group(2).strip()
        code_blocks.append({
            'language': language,
            'content': code_content
        })
    
    return code_blocks

def process_content_with_code(content: str) -> str:
    """
    Process content that may contain code blocks
    
    Args:
        content: String content that may contain code blocks
        
    Returns:
        Processed content with code blocks properly formatted
    """
    if not content:
        return ""
        
    # Extract code blocks
    code_blocks = extract_code_blocks(content)
    
    # Replace code blocks with placeholders
    processed_content = content
    for i, code_block in enumerate(code_blocks):
        placeholder = f"__CODE_BLOCK_{i}__"
        processed_content = processed_content.replace(
            f"```{code_block['language']}\n{code_block['content']}```",
            placeholder
        )
    
    # Process the content (e.g., handle other markdown elements)
    # ...
    
    # Restore code blocks with proper formatting
    for i, code_block in enumerate(code_blocks):
        placeholder = f"__CODE_BLOCK_{i}__"
        formatted_code = f"```{code_block['language']}\n{code_block['content']}\n```"
        processed_content = processed_content.replace(placeholder, formatted_code)
    
    return processed_content

def json_to_markdown(data: Union[Dict, List], heading_level: int = 1) -> str:
    """
    Convert JSON source to Markdown format with support for code blocks, images, and hyperlinks
    
    Args:
        data: JSON source (dict or list)
        heading_level: Current heading level (1-6)
        
    Returns:
        str: Markdown formatted string
    """
    markdown = ""
    
    if isinstance(data, dict):
        # 处理文档标题和介绍
        if "title" in data and "content" in data:
            # 添加主标题
            markdown += f"# {data['title']}\n\n"
            
            # 处理内容部分
            content = data["content"]
            if isinstance(content, dict):
                # 处理介绍
                if "introduction" in content:
                    markdown += f"{content['introduction']}\n\n"
                
                # 处理章节
                if "sections" in content:
                    for section in content["sections"]:
                        if isinstance(section, dict):
                            # 添加章节标题
                            if "title" in section:
                                markdown += f"## {section['title']}\n\n"
                            
                            # 处理章节内容
                            if "content" in section:
                                section_content = section["content"]
                                if isinstance(section_content, str):
                                    markdown += f"{process_content_with_code(section_content)}\n\n"
                                else:
                                    markdown += f"{section_content}\n\n"
                            
                            # 处理图片
                            if "image" in section:
                                image = section["image"]
                                alt_text = image.get("alt", "Image")
                                url = image.get("url", "")
                                title = image.get("title", "")
                                if title:
                                    markdown += f"![{alt_text}]({url} \"{title}\")\n\n"
                                else:
                                    markdown += f"![{alt_text}]({url})\n\n"
                            
                            # 处理代码示例
                            if "code_example" in section:
                                code_data = section["code_example"]["code"]
                                language = code_data.get("language", "")
                                code_content = code_data.get("content", "")
                                markdown += f"```{language}\n{code_content}\n```\n\n"
                            
                            # 处理列表项
                            if "items" in section:
                                for item in section["items"]:
                                    if isinstance(item, dict):
                                        # 处理带链接的列表项
                                        text = item.get("text", "")
                                        description = item.get("description", "")
                                        link = item.get("link", "")
                                        
                                        if link:
                                            if description:
                                                markdown += f"- [{text}]({link}) - {description}\n"
                                            else:
                                                markdown += f"- [{text}]({link})\n"
                                        else:
                                            markdown += f"- {text}\n"
                                    else:
                                        # 处理简单文本列表项
                                        markdown += f"- {item}\n"
                                markdown += "\n"
                            
                            # 处理子章节
                            if "subsections" in section:
                                for subsection in section["subsections"]:
                                    if isinstance(subsection, dict):
                                        # 添加子章节标题
                                        if "title" in subsection:
                                            markdown += f"### {subsection['title']}\n\n"
                                        
                                        # 处理子章节内容
                                        if "content" in subsection:
                                            markdown += f"{subsection['content']}\n\n"
                                        
                                        # 处理子章节的代码示例
                                        if "code_example" in subsection:
                                            code_data = subsection["code_example"]["code"]
                                            language = code_data.get("language", "")
                                            code_content = code_data.get("content", "")
                                            markdown += f"```{language}\n{code_content}\n```\n\n"
                                        
                                        # 处理子章节的列表项
                                        if "items" in subsection:
                                            for item in subsection["items"]:
                                                if isinstance(item, dict):
                                                    text = item.get("text", "")
                                                    description = item.get("description", "")
                                                    link = item.get("link", "")
                                                    
                                                    if link:
                                                        if description:
                                                            markdown += f"- [{text}]({link}) - {description}\n"
                                                        else:
                                                            markdown += f"- [{text}]({link})\n"
                                                    else:
                                                        markdown += f"- {text}\n"
                                                else:
                                                    markdown += f"- {item}\n"
                                            markdown += "\n"
    
    return markdown

def save_json_to_markdown(json_data: Union[Dict, List], output_file: str) -> None:
    """
    Save JSON source to a Markdown file
    
    Args:
        json_data: JSON source to convert
        output_file: Path to the output Markdown file
    """
    markdown = json_to_markdown(json_data)
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(markdown)

def load_json_from_file(file_path: str) -> Union[Dict, List]:
    """
    Load JSON source from a file
    
    Args:
        file_path: Path to the JSON file
        
    Returns:
        Union[Dict, List]: Loaded JSON source
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def main():
    # 从JSON文件加载数据
    json_data = load_json_from_file('chat_client_api.json')
    
    # 转换为Markdown并保存
    save_json_to_markdown(json_data, "chat_client_api.md")
    print("Markdown file has been created successfully!")

if __name__ == "__main__":
    main() 